<template>
  <el-drawer v-model="isDrawer" :width="width" :title="title" direction="rtl" class="w-1/4">
    <el-form
      :model="formParams"
      :rules="rules"
      ref="formRef"
      label-placement="left"
      :label-width="80"
    >
      <el-form-item label="登录账号" prop="uid">
        <el-input
          placeholder="请输入登录账号"
          v-model="formParams.uid"
          :disabled="formParams.id ? true : false"
        />
      </el-form-item>
      <el-form-item label="密码" :prop="getPwdPath">
        <el-input
          type="password"
          show-password-on="mousedown"
          placeholder="请输入密码"
          v-model="formParams.pwd"
        />
      </el-form-item>

      <el-form-item label="角色" prop="roleIds">
        <el-select
          allowClear
          v-model="formParams.roleIds"
          filterable
          remote
          multiple
          @remote-method="roleSearch"
          :loading="roleLoading"
          @blur="getRoleData"
          placeholder="请选择角色"
          class="w-full"
        >
          <el-option
            v-for="item in roleOption"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所在岗位" prop="postId">
        <el-select
          allowClear
          v-model="postName"
          filterable
          remote
          @remote-method="postSearch"
          :loading="postLoading"
          @blur="getPostData"
          @change="postChange"
          placeholder="请选择所在岗位"
          class="w-full"
        >
          <el-option
            v-for="item in postOption"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="所在部门" prop="deptId">
        <el-select
          allowClear
          v-model="deptName"
          filterable
          remote
          @remote-method="deptSearch"
          :loading="deptLoading"
          @blur="getDeptData"
          @change="deptChange"
          placeholder="请选择部门"
          class="w-full"
        >
          <el-option
            v-for="item in deptOption"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="姓名" prop="realName">
        <el-input placeholder="请输入姓名" v-model="formParams.realName" />
      </el-form-item>

      <el-form-item label="手机" prop="mobile">
        <el-input placeholder="请输入手机" v-model="formParams.mobile" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input placeholder="请输入邮箱" v-model="formParams.email" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-radio-group type="button" v-model="formParams.gender" name="genderGroup">
          <el-radio label="MALE">男</el-radio>
          <el-radio label="FEMALE">女</el-radio>
          <el-radio label="UNKNOWN">未知</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="状态" prop="disabled">
        <el-radio-group type="button" v-model="formParams.disabled" name="rdisabledGroup">
          <el-radio :label="false">启用</el-radio>
          <el-radio :label="true">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-space>
        <el-button @click="handleReset()">重置</el-button>
        <el-button type="primary" :loading="subLoading" @click="formSubmit">提交</el-button>
      </el-space>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import type { formParamsType } from './types';

  import { addUser, editUser, userInfo } from '@/api/system/user';
  import { postList } from '@/api/auth/post';
  import { deptList } from '@/api/auth/dept';
  import { roleList } from '@/api/system/role';
  import { cloneDeep } from 'lodash-es';

  const rules = {
    uid: {
      required: true,
      message: '登录帐号不能为空',
      trigger: 'blur',
    },
    pwd: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
  };

  const emit = defineEmits(['change']);

  defineProps({
    title: {
      type: String,
      default: '新增',
    },
    width: {
      type: Number,
      default: 420,
    },
  });

  const subLoading = ref(false);
  const roleLoading = ref(false);
  const roleOption = ref();
  const postOption = ref();
  const deptOption = ref();

  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const postLoading = ref(false);
  const deptLoading = ref(false);
  const postName = ref();
  const deptName = ref();

  const defaultValueRef = () => ({
    id: null,
    uid: '',
    realName: '',
    pwd: '',
    gender: '',
    face: '',
    mobile: '',
    email: '',
    deptId: null,
    postId: null,
    disabled: false,
    roleIds: [],
  });

  const formParams = ref<formParamsType>(defaultValueRef());

  const getPwdPath = computed(() => {
    return !formParams.value.id ? 'pwd' : '';
  });

  async function openDrawer(id?) {
    if (id) {
      formParams.value.id = id;
      getInfo();
      return;
    }
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
    subLoading.value = false;
  }

  function postChange(value) {
    formParams.value.postId = value;
  }

  function deptChange(value) {
    formParams.value.deptId = value;
  }

  function formSubmit() {
    formRef.value.validate((valid) => {
      if (valid) {
        // 克隆
        const params = cloneDeep(formParams.value);
        const msg = params.id ? '编辑成功' : '添加成功';
        subLoading.value = true;
        if (params.id) {
          editUser(params).then((_) => {
            ElMessage.success(msg);
            emit('change');
            handleReset(true);
          });
        } else {
          addUser(params).then((_) => {
            ElMessage.success(msg);
            emit('change');
            handleReset(true);
          });
        }
      } else {
        ElMessage.error('请填写完整信息');
      }
    });
  }

  function handleReset(isClose = false) {
    formRef.value.resetFields();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
    postName.value = '';
    deptName.value = '';
    isClose && closeDrawer();
    subLoading.value = false;
  }

  function getInfo() {
    userInfo(formParams.value.id).then(async (res) => {
      const user = res.user;
      const params = {
        id: formParams.value.id,
        uid: user.uid,
        email: user.email,
        mobile: user.mobile,
        realName: user.realName,
        pwd: '',
        gender: user.gender,
        face: user.face,
        roleIds: user.roles.map((item) => item.id),
        postId: user.postId,
        deptId: user.deptId,
      };
      postName.value = user.post?.name || '';

      deptName.value = user.dept?.name || '';

      formParams.value = Object.assign(formParams.value, params);
      isDrawer.value = true;
    });
  }

  async function getRoleData(params?) {
    const res = await roleList(params);
    roleOption.value = res.list;
    roleLoading.value = false;
  }

  function roleSearch(query: string) {
    roleLoading.value = true;
    getRoleData({ searchKey: 'name', searchValue: query });
  }

  async function getPostData(params?) {
    const res = await postList(params);
    postOption.value = res.list;
    postLoading.value = false;
  }

  function postSearch(query: string) {
    postLoading.value = true;
    getPostData({ searchKey: 'name', searchValue: query });
  }

  async function getDeptData(params?) {
    const res = await deptList(params);
    deptOption.value = res.list;
    deptLoading.value = false;
  }

  function deptSearch(query: string) {
    deptLoading.value = true;
    getDeptData({ searchKey: 'name', searchValue: query });
  }

  onMounted(async () => {
    getRoleData();
    getPostData();
    getDeptData();
  });

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
